/**
 * 字符串解析类
 */
package cn.antia.util;

import java.util.*;

/**
 * @author pc
 * @date Jan 31, 2008
 * @time 10:31:21 AM
 */
public class StringParser {
	public static String parseSql(String sql,String rowNum){
		boolean isSQNormal = true;
		boolean isBracketNoraml =true;
		String UPPERSQL = sql.toUpperCase().trim();
		//定位 ' FROM ' 串的位置
		int fromPosition = UPPERSQL.indexOf(" FROM ");
		for(int i = 0;i<sql.length();i++){
			String s = sql.substring(i, i+1);
			if(isBracketNoraml){
				if(s.equals("(")){
					isBracketNoraml = false;
				}
			}else if(s.equals(")")){
				isBracketNoraml = true;
			}
			if(isSQNormal){
				if(s.equals("'")){
					isSQNormal = false;
				}
			}else if(s.equals("'")){
				isSQNormal = true;
			}
			//如果已经到了　FROM　串的位置，但是字符串正在某一个整体当中
			if(fromPosition == i){
				if(isSQNormal && isBracketNoraml){
					break;
				}else{
					fromPosition = UPPERSQL.indexOf(" FROM ", i+1);
					if(fromPosition == -1){
						System.out.println(" error ----- ");
					}
				}
			}
		}
		//插入 rowNum 串
		return sql.substring(0,fromPosition)+ "," + rowNum + sql.substring(fromPosition, sql.length());
	}
	

	public static List parse(String str, String token,Map<String, String> ignoreRule) {
		System.out.println("Getting strart:" + str);
		List result = new ArrayList();
		Iterator iterator = ignoreRule.keySet().iterator();
		Map keyTemp = new HashMap();
		String sub;
		int start = 1000;
		int lastIndex = 0;
		int end = -1;
		int st, et; // 临时的开始下标与结束下标
		String tk, tv; // key
		String value = "";
		boolean dow = true;
		do {
			// 检查是否需要循环
			dow = true;
			while (iterator.hasNext()) {
				tk = (String) iterator.next();
				tv = ignoreRule.get(tk);
				if (str.indexOf(tk) > -1 && str.indexOf(tv, str.indexOf(tk) + 1) > -1) {
					System.out.println("while : st:" + tk + " V:" + tv);
					dow = false;
					break;
				}
			}
			if (dow)
				break;
			// 循环查找第一个下标
			Iterator iterator2 = ignoreRule.keySet().iterator();
			while (iterator2.hasNext()) {
				tk = (String) iterator2.next();
				tv = ignoreRule.get(tk);
				st = str.indexOf(tk);
				if (st > -1) {
					et = str.indexOf(tv, st + 1);
					System.out.println("st:" + st + " et:" + et + " K:" + tk + " V:" + tv);
					if (et <= st) {
						break;
					}
					if (st < start) {
						value = tv;
						start = st;
						end = et;
					}
					if (st > lastIndex) {
						lastIndex = st;
					}
				}
			}
			if (start < 1000) {
				sub = str.substring(start, end + value.length());
				if (sub.indexOf(token) > -1) {
					System.out.println("operate ...sub:" + sub);
					String goat = getStringNotContains(str, token);
					str = replace(str, goat, start, end + value.length());
					keyTemp.put(goat, sub);
				}
				start = 1000;
			}
		} while (!dow);

		System.out.println("Finished checked:" + str);
		// -----//
		// split
		Iterator tks;
		String[] ss = str.split(token);
		String s, goat, v;
		for (int i = 0; i < ss.length; i++) {
			s = ss[i];
			tks = keyTemp.keySet().iterator();
			while (tks.hasNext()) {
				goat = (String) tks.next();
				v = (String) keyTemp.get(goat);
				s = s.replace(goat, v);
			}
			result.add(s);
		}
		// 还原-----------还原
		/*
		 * tks = keyTemp.keySet().iterator(); while(tks.hasNext()) { s =
		 * (String) tks.next(); v = (String) keyTemp.get(s); str =
		 * str.replace(s, v); } System.out.println("Finished reverted:" + str);
		 */
		return result;
	}

	public static void main(String[] args) {
		/*
		 * String str = "aaasssddd"; System.out.println(str.indexOf("sss"));;
		 * str = replace(str,"sss",3,6); System.out.println(str);
		 */
		/*
		String str = "aaa,ddd,sss,[yes,yes],fff{kkjjhytrsd,llk},[yes,yes]";
		String s2 = "select id,name,code,parent,' from - 09' from area where id in(select sid from a);";
		Map map = new HashMap();
		//map.put("select", " from");
		map.put("[", "]");
		map.put("{", "}");
		// map.put("{","}");
		long start = System.currentTimeMillis();
		List list = StringParser.parse(str, ",", map);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Object o = iterator.next();
			System.out.println(o);
		}
		System.out.println("end:spent time:"
				+ (System.currentTimeMillis() - start));
		System.out.println("");
		System.out.println("");*/
		String sql = "Select UserID,' select from as ( asdd )'+LoginName as ln,DAY(CreateTime) as regDay fRom B_User";
		String rowNum = "ROW_NUMBER() Over(order by UserID desc) as rowNum";
		String newsql = parseSql(sql,rowNum);
		System.out.println("New sql:" + newsql);
	}

	public static String replace(String str, String replacement, int start,
			int end) {
		String s1 = str.substring(0, start);
		String s3 = str.substring(end);
		StringBuffer buffer = new StringBuffer(s1).append(replacement).append(
				s3);
		return buffer.toString();
	}

	private static String getStringNotContains(String str, String token) {
		Random r = new Random();
		int i;
		String sub;
		do {
			i = r.nextInt(999999);
			sub = i + "";
		} while (str.indexOf(sub) > -1 && sub.indexOf(token) > -1);
		return sub;
	}
	
	
	

}